import axios from "axios"
import Vue from "vue"
import router from "../router"
import store from "../store"
import { errorAlert } from "../utils/alert"

// 配置环境
if(process.env.NODE_ENV==="development"){
    Vue.prototype.$pre = "http://localhost:2000"
}else{
    Vue.prototype.$pre = ""
}

// 请求拦截
axios.interceptors.request.use(config=>{
    if(config.url!="/api/userlogin"){
        config.headers.authorization = store.getters.info.token
    }
    return config
})

// 请求响应
axios.interceptors.response.use(res=>{
    console.group("本次请求发起地址是"+res.config.url)
    console.log(res)
    console.groupEnd()
    if(res.data.code!=200){
        errorAlert(res.data.msg)
    }

    if(res.data.msg === "登录已过期或访问权限受限"){
        store.dispatch("changeInfo",{})
        router.replace("/login");
    }

    return res
})

// 封装请求
export const get =(url,params={})=> {
    return axios({
        url,
        method:"get",
        params
    })
}

export const post = (url,params,haveFile=false)=>{
    let data=null;
    if(haveFile){
        data=new FormData()
        for(let k in params){
            data.append(k,params[k])
        }
    }else{
        data=params
    }
    return axios({
        url,
        method:"post",
        data
    })
}